package com.decoration.basic.controller.api;

import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.decoration.basic.BasicController;
import com.decoration.basic.findCondition.DecUserFindCondition;
import com.decoration.basic.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.decoration.basic.entity.DecorationUser;
import com.decoration.basic.entity.JsonResult;
import com.decoration.basic.service.DecUserService;

@RestController
@RequestMapping("/api")
public class DecUserController  extends BasicController {

	// 日志记录器
	private static final Logger log = LoggerFactory.getLogger(DecUserController.class);

	@Resource(name = "DecUserService")
	private DecUserService decUserService;

	/** 
	 * 用戶登录接口,返回用户菜单列表
	 */
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult login(JsonResult jsonResult, @RequestBody DecorationUser users, HttpServletRequest request) {
		if (users.getPerAccount() == null || "".equals(users.getPerAccount())) {
			jsonResult.setMsg("登录账号不能为空");
			jsonResult.setCode(JsonResult.FAILED_CODE);
			return jsonResult;
		}
		if (users.getPerPasswd() == null || "".equals(users.getPerPasswd())) {
			jsonResult.setMsg("登录密码不能为空");
			jsonResult.setCode(JsonResult.FAILED_CODE);
			return jsonResult;
		}
		DecorationUser user = decUserService.findByPhone(users.getPerAccount());
		jsonResult.setMsg("账号或密码错误,请重试");
		jsonResult.setCode(JsonResult.FAILED_CODE);
		if (user == null) {
			return jsonResult;
		}
		// 校验用户类型,只有代理商和代理商业务员才能登录APP端
		///////////////////////////////
		/////////// 待处理哪些账户可以成小程序登陆///////////////
		/////////////////////////
//		if (user.getPerType() == Global.USER_MANAGER) {
//			jsonResult.setMsg("账号类型错误,请更换账号后重试");
//			return jsonResult;
//		}
		// 密码校验
		if (!user.getPerPasswd().equals(MD5Util.getMD5(user.getPerSalt(), users.getPerPasswd()))) {
//		if (!user.getPerPasswd().equals(users.getPerPasswd())) {
			return jsonResult;
		}

		// 已经登陆过的，则销毁原来的session
		// SessionSingleton.getInstance().checkSession(user.getUserId(),
		// request.getSession());

		// 保存当前用户信息
		request.getSession().setAttribute(Global.SESSION_USER_ID, user.getUserId());
		request.getSession().setAttribute(Global.SESSION_USER_NAME, user.getPerName());
		request.getSession().setAttribute(Global.SESSION_USER_ACCOUNT, users.getPerAccount());
		request.getSession().setAttribute(Global.SESSION_USER_TYPE, user.getPerType());
		request.getSession().setMaxInactiveInterval(60 * 60 * 24 * 15 * 1000); //

		// 保存已登录账号的session
		SessionSingleton.getInstance().putClientSession(user.getUserId(), request.getSession());
		// 以秒为单位，即在没有活动120分钟后，session将失效
		jsonResult.setMsg("登录成功");
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setData(user);
		return jsonResult;
	}

	/**
	 *
	 */
	@RequestMapping(value = "/user/update", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult updateUser(JsonResult jsonResult, @RequestBody DecorationUser user) {
		if (null == user || "".equals(user)) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要修改的用户信息为空,请重试!");
			return jsonResult;
		}
		if (null == user.getUserId() || "".equals(user.getUserId())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要修改的账号信息为空,请重试!");
			return jsonResult;
		}
		if (null == user.getPerPasswd() || "".equals(user.getPerPasswd())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("需要修改的密码为空,请重试!");
			return jsonResult;
		}
		// 生成8位随机数
		StringBuilder perSalt = new StringBuilder();
		Random random = new Random();
		// 随机生成数字，并添加到字符串
		for (int i = 0; i < 8; i++) {
			perSalt.append(random.nextInt(10));
		}
		String perPasswd = MD5Util.getMD5(perSalt.toString(), user.getPerPasswd());
		user.setPerPasswd(perPasswd);
		user.setPerSalt(perSalt.toString());
		Boolean bSuc = decUserService.update(user);
		if (bSuc == false) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("修改密码失败,请重试!");
			return jsonResult;
		}
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("密码修改成功");
		return jsonResult;
	}

	/**
	 *
	 */
	@RequestMapping(value = "/user/exit", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult doExit(JsonResult jsonResult, HttpServletResponse response, HttpSession session,
			@RequestBody DecorationUser users, HttpServletRequest request) {
		if (users.getPerAccount() == null || "".equals(users.getPerAccount())) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("退出账号不允许为空，请重新输入!");
			return jsonResult;
		}

		// 查询该用户的数据是否存在
		DecorationUser user = decUserService.findByPhone(users.getPerAccount());
		if (user == null) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("账号不存在,账号退出失败!");
			return jsonResult;
		}

		// 判断账号是否已经登陆
		SessionSingleton.getInstance().removeClientSession(user.getUserId(), session);

		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("账号退出成功!");
		return jsonResult;
	}

	/**
	 *
	 */
	@PostMapping("/userlogin")
	public JsonResult getWXAccessUser(JsonResult jsonResult, String encryptedData, String code, String iv,
			HttpServletRequest request) {
		/*
		 * StringBuffer buffer = new StringBuffer(); //一、参数解析
		 * buffer.append("https://api.weixin.qq.com/sns/jscode2session?"); try {
		 * buffer.append("appid=" + ExternalConfig.get("appid"));
		 * buffer.append("&secret=" + ExternalConfig.get("secret"));
		 * buffer.append("&js_code=" + code);
		 * buffer.append("&grant_type=authorization_code"); } catch (IOException e) {
		 * log.error("获取appid等参数时异常: {}", e.getMessage(), e); return
		 * JsonResult.set().buildFailedResponse("参数错误！"); } //二、请求地址并且获得返回值 String
		 * tokenResult = HttpTookit.doGet(buffer.toString()); //将其转化为Map格式 Map map =
		 * JSON.parseObject(tokenResult, Map.class); //会话密钥（最关键的是openid和session_key）
		 * String openId = (String) map.get("openid"); String session_key = (String)
		 * map.get("session_key"); if (StringUtils.isNullOrEmpty(openId)) {
		 * log.error("获取openid错误：{}", tokenResult); return
		 * ResponseVoBuilderFactory.getBuilder().buildFailedResponse(""); }
		 * //三、判断用户是否已经微信注册过,使用unionid，用来保证小程序授权得到同一个用户 String unionid = (String)
		 * map.get("unionid"); Map<String, Object> params = new HashMap<>();
		 * params.put("userWechatAccount", unionid); TAppUser appuser =
		 * userService.getAppuser(params); ICacheAdapter cacheManager =
		 * CacheAdapterFactory.getCacheAdapter(); if (appuser != null) { Map<String,
		 * Object> userData = buildUserData(appuser, cacheManager, request);
		 * //直接返回已经注册用户的信息 return
		 * ResponseVoBuilderFactory.getBuilder().build().setBody(userData); }
		 * //四、未注册过，则解密用户信息 if (ObjectUtil.isNotEmpty(map.get("openid")) &&
		 * ObjectUtil.isNotEmpty("session_key")) { JSONObject userInfoJson =
		 * WechatGetUserInfoUtil.getUserInfo(encryptedData, session_key, iv); if
		 * (userInfoJson != null) { //注册 AppUserRegisterBuilder builder = new
		 * AppUserRegisterBuilder.Builder().openId((String) userInfoJson.get("openid"))
		 * .nickName((String) userInfoJson.get("nickName")) .sex((Integer)
		 * userInfoJson.get("sex")) .type(1) .build(); TAppUser register =
		 * register(builder); Map<String, Object> userData = buildUserData(register,
		 * cacheManager, request); return
		 * ResponseVoBuilderFactory.getBuilder().build().setBody(userData); } }
		 * log.error("获取用户信息失败"); return
		 * ResponseVoBuilderFactory.getBuilder().buildFailedResponse("获取用户信息失败");
		 */

		JSONObject loginuser = null;
		JSONObject userinfo = null;
		try {
			loginuser = WechatGetUserInfoUtil.getWechatSmallProgram(code);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("微信登录失败");
			return jsonResult;
		}
		// 确定返回信息
		String session_key = loginuser.getString("session_key");
		String openid = loginuser.getString("openid");
		String unionid = loginuser.getString("unionid");
		log.info("session_key: " + session_key + ",openid: " + openid + ",unionid: " + unionid);
		log.info("wechat response data: " + loginuser.toString());

		String signature = request.getParameter("signature");
		log.info(signature);
		// if (signature.equals())
		try {
			userinfo = WechatGetUserInfoUtil.getUserInfo(encryptedData, session_key, iv);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("微信登录获取用户信息失败");
			return jsonResult;
		}

		String niceName = userinfo.getString("niceName");

		// 返回用户相关内容
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("sucess login!");
		return jsonResult;
	}

	/**
	 *
	 */
	@PostMapping("/tellogin")
	public JsonResult getWXAccessPhone(JsonResult jsonResult, String encryptedData, String code, String iv) {

		// 获取微信登录
		JSONObject loginuser = WechatGetUserInfoUtil.getWechatSmallProgram(code);
		if (loginuser == null) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("微信登录失败");
			return jsonResult;
		}
		// 确定返回信息
		String session_key = loginuser.getString("session_key");
		String openid = loginuser.getString("openid");
		String unionid = loginuser.getString("unionid");
		log.info("session_key: " + session_key + ",openid: " + openid + ",unionid: " + unionid);
		log.info("wechat response data: " + loginuser.toString());

		// 获取手机号
		JSONObject telinfo = WechatGetUserInfoUtil.getUserInfo(encryptedData, session_key, iv);
		if (telinfo == null) {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("用户登录失败，请联系管理员!");
			return jsonResult;
		}

		String purePhoneNumber = telinfo.getString("purePhoneNumber");
		Integer sum = decUserService.sumByPhone(purePhoneNumber);
		if (sum == 0) {
			DecorationUser userinfo = new DecorationUser();
			userinfo.setPerAccount(purePhoneNumber);
			userinfo.setWalterAccount(openid);
			userinfo.setWalterName(session_key);
			userinfo.setPerType(5);
			userinfo.setCreateTime(new Date());
			userinfo.setUpdateTime(new Date());
			userinfo.setCreateId("system");
			userinfo.setUpdateId("system");
			Boolean result = decUserService.add(userinfo);
			if (result) {
				jsonResult.setCount(1);
				jsonResult.setData(userinfo);
			} else {
				jsonResult.setCode(JsonResult.FAILED_CODE);
				jsonResult.setMsg("用户登录失败，请联系管理员!");
				return jsonResult;
			}
		} else if (sum == 1) {
			// 返回用户相关信息
			DecorationUser userinfo = decUserService.findByPhone(purePhoneNumber);
			jsonResult.setCount(1);
			jsonResult.setData(userinfo);
		} else {
			jsonResult.setCode(JsonResult.FAILED_CODE);
			jsonResult.setMsg("用户登录信息异常，请联系管理员!");
			return jsonResult;
		}

		// 返回用户相关内容
		jsonResult.setCode(JsonResult.SUCCESS_CODE);
		jsonResult.setMsg("Welcome login!");
		return jsonResult;
	}

	/**
	 * 小程序用户列表查询
	 */
	@RequestMapping(value = "/user/list", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult getUserList(@RequestBody DecUserFindCondition findCondition) {
		setPagerInfo(findCondition);
		Integer count = null;
		try {
			count = decUserService.getUserSize(findCondition);
		} catch (Exception e) {
			return Faild("参数校验异常，数据库操作失败，请联系管理员");
		}
		List<DecorationUser> list = null;
		if (!StringUtil.isEmpty(count) && count > 0) {
			list = decUserService.getUserList(findCondition);
			// 时间格式化,清除原始时间,清除密码
			for (DecorationUser commission : list) {
				commission.setPerPasswd(null);
				commission.setPerSalt(null);
			}
		}

		return Sucess(count,"交易成功！",list);
	}

	@RequestMapping(value = "/user/designer/list", method = RequestMethod.POST)
	@ResponseBody
	public JsonResult getDesignerUserList(@RequestBody DecUserFindCondition findCondition) {
		setPagerInfo(findCondition);
		findCondition.setPerType(4);
		Integer count = null;
		try {
			count = decUserService.getUserSize(findCondition);
		} catch (Exception e) {
			return Faild("参数校验异常，数据库操作失败，请联系管理员");
		}
		List<DecorationUser> list = null;
		if (!StringUtil.isEmpty(count) && count > 0) {
			list = decUserService.getDesignUserList(findCondition);
			// 时间格式化,清除原始时间,清除密码
			for (DecorationUser commission : list) {
				commission.setPerPasswd(null);
				commission.setPerSalt(null);
			}
		}

		return Sucess(count,"交易成功！",list);
	}

}
